/**
 * @Description: 合并配置
 * @Author: Zander
 * @Date: 2022/11/29 10:49
 * @LastEditors: Zander
 * @LastEditTime: 2022/11/29 10:49
 */
import { isUndefined } from '@utils/verify';
import { commonUtils } from '@utils/common';

/**
 * 合并局部配置优先的配置，如果局部有该配置项则用局部，如果全局有该配置项则用全局
 * @param {Array} keys 配置项
 * @param {Object} globalConfig 当前的全局配置
 * @param {Object} conf 局部配置
 * @returns {{}}
 */
const mergeKeys = (keys, globalConfig, conf) => {
  const config = {};
  keys.forEach((prop) => {
    if (!isUndefined(conf[prop])) {
      config[prop] = conf[prop]
    } else if (!isUndefined(globalConfig[prop])) {
      config[prop] = globalConfig[prop]
    }
  })
  return config;
}

/**
 * 合并配置
 * @param globalConfig 当前实例的全局配置
 * @param conf 当前的局部配置
 * @returns {{baseURL, method: *|string, custom: {}, header: {}, params, url}}
 */
// eslint-disable-next-line complexity
export default (globalConfig, conf = {}) => {
  const method = conf.method || globalConfig.method || 'GET';
  let config = {
    baseURL: globalConfig.baseURL || '',
    method,
    url: conf.url || '',
    params: conf.params || {},
    custom: { ...(globalConfig.custom || {}), ...(conf.custom || {}) },
    header: commonUtils.merge(globalConfig.header || {}, conf.header || {})
  };
  const defaultToConfig2Keys = ['getTask', 'validateStatus'];
  config = { ...config, ...mergeKeys(defaultToConfig2Keys, globalConfig, conf) };

  // eslint-disable-next-line no-empty
  if (method === 'DOWNLOAD') {
    // #ifdef H5 || APP-PLUS
    if (!isUndefined(conf.timeout)) {
      config.timeout = conf.timeout;
    } else if (!isUndefined(globalConfig.timeout)) {
      config.timeout = globalConfig.timeout;
    }
    // #endif

    return config;
  }

  if (method === 'UPLOAD') {
    delete config.header['content-type']
    delete config.header['Content-Type']
    const uploadKeys = [
      // #ifdef APP-PLUS || H5
      'files',
      // #endif
      // #ifdef MP-ALIPAY
      'fileType',
      // #endif
      // #ifdef H5
      'file',
      // #endif
      'filePath',
      'name',
      // #ifdef H5 || APP-PLUS
      'timeout',
      // #endif
      'formData'
    ]
    uploadKeys.forEach((prop) => {
      if (!isUndefined(conf[prop])) {
        config[prop] = conf[prop];
      }
    })
    // #ifdef H5 || APP-PLUS
    if (isUndefined(config.timeout) && !isUndefined(globalConfig.timeout)) {
      config.timeout = globalConfig.timeout
    }
    // #endif

    return config;
  }

  const defaultsKeys = [
    'data',
    // #ifdef H5 || APP-PLUS || MP-ALIPAY || MP-WEIXIN
    'timeout',
    // #endif
    'dataType',
    // #ifndef MP-ALIPAY
    'responseType',
    // #endif
    // #ifdef APP-PLUS
    'sslVerify',
    // #endif
    // #ifdef H5
    'withCredentials',
    // #endif
    // #ifdef APP-PLUS
    'firstIpv4'
    // #endif
  ]
  config = { ...config, ...mergeKeys(defaultsKeys, globalConfig, conf) }

  return config;
}
